<?php

/**
 * 银行卡管理
 */

namespace app\member\middle;


class CardMiddle extends \app\base\middle\BaseMiddle {


    private $info = [];
    private $realInfo = [];
    private $userId = 0;

    private function getReceive() {
        $type = intval($this->params['val_type']);
        $userInfo = $this->params['user_info'];
        if (!$type) {
            $receive = $userInfo['tel'];
        } else {
            $receive = $userInfo['email'];
        }
        return $receive;
    }

    private function getInfo() {
        if ($this->info) {
            return $this->info;
        }
        $this->userId = intval($this->params['user_id']);
        $this->info = target('member/PayCard')->getWhereInfo([
            'A.user_id' => $this->userId
        ]);

        $this->realInfo = target('member/MemberReal')->getWhereInfo([
            'A.user_id' => $this->userId
        ]);
        return true;
    }

    protected function meta() {
        $this->setMeta('我的银行卡');
        $this->setName('我的银行卡');
        $this->setCrumb([
            [
                'name' => '会员中心',
                'url' => url('member/index/index')
            ]
        ],[
            [
                'name' => '我的银行卡',
                'url' => url()
            ]
        ]);
        return $this->run([
            'pageInfo' => $this->pageInfo
        ]);
    }

    protected function info() {
        $this->getInfo();
        return $this->run([
            'info' => $this->info,
            'realInfo' => $this->realInfo,
            'bankList' => target('member/PayBank')->loadList()
        ]);
    }


    protected function post() {
        $this->getInfo();
        if(empty($this->info) || empty($this->realInfo)) {
            return $this->stop('请先完成认证！');
        }
        $label = $this->params['label'];
        $bankInfo = target('member/PayBank')->getWhereInfo([
            'label' => $label
        ]);
        if(empty($bankInfo)) {
            return $this->stop('开户银行不存在！');
        }
        $receive = $this->getReceive();
        if (empty($receive)) {
            return $this->stop('该验证方式未绑定，请使用其他验证方式！');
        }
        if (!target('member/Member', 'service')->checkVerify($receive, $this->params['code'], 2)) {
            return $this->stop(target('member/Member', 'service')->getError());
        }
        $data = [
            'user_id' => $this->userId,
            'name' => $bankInfo['name'],
            'label' => $bankInfo['label'],
            'account' => $this->params['account'],
            'account_tel' => $this->params['account_tel'],
            'account_bank' => $this->params['account_bank'],
            'account_name' => $this->realInfo['name'],
            'card_id' => $this->info['card_id']
        ];
        if(!target('member/PayCard')->saveData('edit', $data)) {
            return $this->stop(target('member/PayCard')->getError());
        }
        return $this->run([], '银行卡保存成功！');
    }
}